//
//  ViewController.m
//  MyAFNetworking
//
//  Created by fuyoufang on 15/12/9.
//  Copyright © 2015年 深圳－真二网. All rights reserved.
//

#import "ViewController.h"
#import "UIImageView+WebCache.h"
#import "UIImageView+AFNetworking.h"
#import "AFHTTPSessionManager.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:@""];
    UIImageView *iv = [[UIImageView alloc] init];
    [iv sd_setImageWithURL:url placeholderImage:nil];
    
    [iv setImageWithURL:url placeholderImage:nil];
    
    [self getGET];
    
    NSString *urlStr2 = @"http://www.baidu.com";
    NSURL *url2 = [NSURL URLWithString:urlStr2];
    NSLog(@"%@", url2.absoluteString);
    if (url2.path.length > 0 || ![url2.absoluteString hasSuffix:@"/"]) {
        url2 = [url2 URLByAppendingPathComponent:@""];
        NSLog(@"%@", url2.absoluteString);
    }
}

- (void)getGET {
    NSString *urlStr = @"http://www.weather.com.cn/data/sk/101010100.html";
    
    AFHTTPSessionManager *sessionM = [[AFHTTPSessionManager alloc] init];
    AFHTTPRequestSerializer *requestSerializer = [[AFHTTPRequestSerializer alloc] init];
    requestSerializer.timeoutInterval = 30;
    sessionM.requestSerializer = requestSerializer;
    sessionM.responseSerializer = [AFJSONResponseSerializer serializer];
    sessionM.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    

    NSURLSessionDataTask *dataTask = [sessionM GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%@", downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

- (void)uploadFile {
    NSString *urlStr = @"";
    NSURL *baseUrl = [NSURL URLWithString:@""];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSData *data = [[NSData alloc] init];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseUrl];
    [manager uploadTaskWithRequest:request fromData:data progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
    }];
    
    NSURL *fileUrl = [NSURL fileURLWithPath:@""];
    [manager uploadTaskWithRequest:request fromFile:fileUrl progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
    }];
    
    //NSURLSessionConfiguration *con = [NSURLSessionConfiguration defaultSessionConfiguration];
    //NSLog(@"%f, %f", con.timeoutIntervalForRequest, con.timeoutIntervalForResource);
    //NSURLSession *session = [NSURLSession sessionWithConfiguration:con];

}


- (void)postFile {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // (1)发送 data 数据
        /*
         Data: 需要上传的数据
         name: 服务器参数的名称
         fileName: 文件名称
         mimeType: 文件的类型
         */
        UIImage *image =[UIImage imageNamed:@"minion_02"];
        NSData *data = UIImagePNGRepresentation(image);
        [formData appendPartWithFileData:data name:@"file" fileName:@"abc.png" mimeType:@"image/png"];
        
        // (2)发送 二进制文件
        NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/CertificateSigningRequest.certSigningRequest"];
        // 任意的二进制数据MIMEType application/octet-stream
        // [formData appendPartWithFileURL:url name:@"file" fileName:@"abc.cer" mimeType:@"application/octet-stream" error:nil];
        [formData appendPartWithFileURL:url name:@"file" error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)download {
    NSURL *url = [NSURL URLWithString:@""];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%@", downloadProgress);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        /*!
         @method suggestedFilename
         @abstract Returns a suggested filename if the resource were saved to disk.
                    在资源被保存到硬盘上时，返回一个建议的名称。
         @discussion The method first checks if the server has specified a filename using the
         content disposition header. If no valid filename is specified using that mechanism,
         this method checks the last path component of the URL. If no valid filename can be
         obtained using the last path component, this method uses the URL's host as the filename.
         If the URL's host can't be converted to a valid filename, the filename "unknown" is used.
         In mose cases, this method appends the proper file extension based on the MIME type.
         This method always returns a valid filename.
         这个方法首先检查服务器在部署头部指定的文件名。
         如果这个种机制没有找到合适的文件名，这个方法将会 URL 最后的文件路径。
         如果 URL 的主机不能转换成一个有效的文件名，将会使用 'unknown' 作为文件的名称。
         在大多数情况下，这个方法将会基于 MIME type 
         这个方法之后会返回一个有效的文件名称。
         @result A suggested filename to use if saving the resource to disk.
         在将文件保存到硬盘是提供一个建议的文件名称
         */
        //@property (nullable, readonly, copy) NSString *suggestedFilename;
        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:path];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"%@,   %@", filePath, error);
    }];
}

- (void)sessionDownload {
    NSURL *url = [NSURL URLWithString:@""];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 通过下载成功的地址，拷贝一份到其他地方。
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
        NSURL *newFileLocation = [documentsDirectoryURL URLByAppendingPathComponent:[[response URL] lastPathComponent]];
        [[NSFileManager defaultManager] copyItemAtURL:location toURL:newFileLocation error:nil];
    }];
    
    [downloadTask resume];
}

- (void)sessionUpload {
    NSURL *url = [NSURL URLWithString:@""];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSData *data = nil;
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
    }];
}


- (void)downloadResume {
    
}

@end
